package com.neouton.crm.managerReceiptRecord.service.impl;

import cn.afterturn.easypoi.excel.entity.TemplateExportParams;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.PageDTO;
import com.neouton.common.entity.ActivitiVO;
import com.neouton.common.util.*;
import com.neouton.crm.approval.entity.ApprovalVO;
import com.neouton.crm.approval.service.IApprovalService;
import com.neouton.crm.dictionary.entity.DictionaryLookupItemVO;
import com.neouton.crm.dictionary.service.IDictionaryService;
import com.neouton.crm.entity.NoticVo;
import com.neouton.crm.entity.SysUserEntity;
import com.neouton.crm.executiceManager.entity.ManagerPurchaseOrderVO;
import com.neouton.crm.executiceManager.service.IManagerPurchaseOrderService;
import com.neouton.crm.managerPayPlan.entity.ManagerPayPlan;
import com.neouton.crm.managerPayPlan.service.ManagerPaymentPlanService;
import com.neouton.crm.managerReceiptRecord.entity.ManagerReceiptRecord;
import com.neouton.crm.managerReceiptRecord.entity.ManagerReceiptTable;
import com.neouton.crm.managerReceiptRecord.mapper.ManagerReceiptMapper;
import com.neouton.crm.managerReceiptRecord.service.ManagerReceiptService;
import com.neouton.crm.paymentPlan.entity.PaymentPlan;
import com.neouton.crm.pm.entity.PurchaseOrderVO;
import com.neouton.crm.product.mapper.ProductInfoMapper;
import com.neouton.crm.receiptRecords.entity.ReceiptRecords;
import com.neouton.crm.receiptRecords.entity.ReceiptTable;
import com.neouton.crm.supplier.entity.SupplierVO;
import com.neouton.crm.transpondEmail.entity.TranspondEmailVO;
import com.neouton.crm.transpondEmail.mapper.TranspondEmailMapper;
import com.neouton.crm.transpondEmail.service.TranspondEmailService;
import com.neouton.feginClient.FeginMessageService;
import com.neouton.feginClient.FeginService;
import com.neouton.feginClient.WorkFlowFeginService;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.beans.factory.config.YamlPropertiesFactoryBean;
import org.springframework.core.io.ClassPathResource;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.math.BigDecimal;
import java.sql.Timestamp;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.concurrent.CompletableFuture;

@Service
public class ManagerReceiptServiceImpl  implements ManagerReceiptService {

    @Resource
    private IDictionaryService dictionaryService;
    @Resource
    private IApprovalService approvalService;
    @Resource
    private FeginMessageService feginMessageService;

    @Resource
    private WorkFlowFeginService workFlowFeginService;
    @Resource
    private ManagerReceiptMapper managerReceiptMapper;

    @Resource
    private ManagerPaymentPlanService managerPaymentPlanService;
    @Resource
    FeginService feginService;

    @Resource
    private ProductInfoMapper productInfoMapper;
    @Resource
    private IManagerPurchaseOrderService managerPurchaseOrderService;

    @Resource
    private TranspondEmailMapper transpondEmailMapper;

    @Resource
    private TranspondEmailService transpondEmailService;

    @Value("${webSit.web}")
    private String webSitUrl;

    @Override
    public ManagerReceiptRecord saveManagerReceiptRecord(ManagerReceiptRecord entity, String token) {

        //1.发起工作流
        //1）获取下一审批人，暂定总经理
        //获取审批人
        SysUserEntity user = dictionaryService.queryMenuUserIdsByCode("administrativeSpecialist").get(0);
        //获取人员信息
        Integer businessId = this.startManagerReceiptRecordApproval(user);
        //2.记录本地审批数据
        //生成审批主表信息，日志信息
        ApprovalVO approval = approvalService.initApprovalAndLog(businessId, 42, entity.getAskReason(), "",
                user.getUserId(),"");
        //之后更新/保存
        entity.setApprovalId(approval.getApprovalId());
        if(entity.getSupplier() !=  null) {
            entity.setSupplierId(entity.getSupplier().getSupplierId());
        }
        //判断是新增提交还是编辑提交
        if(entity.getReceiptRecordsId()!= null){
            //根据采购单id判断是否存在中间表
            if(entity.getPurchaseOrderId() != null){
                //备份收票记录、票据明细等数据
                List<ManagerReceiptTable> list =  new ArrayList<>() ;
                List<ManagerPayPlan> paymentPlans =  new ArrayList<>() ;
                //处理中间表数据

                //将收票的状态反写回付款计划中
                ManagerReceiptRecord managerReceiptRecord = managerReceiptMapper.queryManagerReceiptRecordByID(entity.getReceiptRecordsId());
                managerReceiptMapper.backUpManagerReceiptRecord(managerReceiptRecord.getReceiptRecordsId(), AuthUtils.getUserId());
                managerReceiptMapper.backUpReceiptTable(managerReceiptRecord.getReceiptRecordsId(), AuthUtils.getUserId());
                managerReceiptMapper.updateManagerReceiptRecordById(entity);
                List<ManagerReceiptTable> receiptTables = new ArrayList<>();
                for (ManagerReceiptTable rece: entity.getReceiptTables()) {
                    rece.setApprovalId(entity.getApprovalId());
                    ManagerPayPlan paymentPlan = new ManagerPayPlan();
                    paymentPlan.setPlanPeriod(rece.getPlanPeriod());
                    paymentPlan.setPurchaseOrderId(entity.getPurchaseOrderId());
                    if(rece.getReceiptRecordsId() == null){
                        rece.setReceiptRecordsId(entity.getReceiptRecordsId());
                        rece.setPurchaseOrderId(entity.getPurchaseOrderId());
                        rece.setPayPlanId(managerPaymentPlanService.queryPaymentPlanByPurchaseOrderID(paymentPlan).getPayPlanId());
                    }

                    List<ManagerReceiptTable> receiptTableList =queryReceiptTablesByIdAndPlanPeriod(rece);
                    BigDecimal num = new BigDecimal("0");
                    if(receiptTableList.size()>0){
                        for (ManagerReceiptTable rt:receiptTableList) {
                            num= num.add(new BigDecimal(rt.getReceiptMoney())) ;
                        }
                    }else {
                        num= num.add(new BigDecimal(rece.getReceiptMoney()));
                    }
                    //num = num.subtract(new BigDecimal(rece.getReceiptMoney()));
                    if(num.compareTo(new BigDecimal(rece.getPlanMoney())) == 1){
                        paymentPlan.setReceiveInvoice(0);
                    } else if(num.compareTo(new BigDecimal(rece.getPlanMoney())) == 0) {
                        paymentPlan.setReceiveInvoice(0);
                    } else{
                        paymentPlan.setReceiveInvoice(2);
                    }
                    paymentPlan.setPurchaseId(entity.getPurchaseOrderId());
                    paymentPlans.add(paymentPlan);
                    list.add(rece);
                }
                managerPaymentPlanService.updatePayPlansByIdAndPlanPeriod(paymentPlans);
                managerReceiptMapper.updateReceiptTableDataById(list,entity.getReceiptRecordsId());

            }else{
                //修改收票记录数据
                ManagerReceiptRecord managerReceiptRecord = managerReceiptMapper.queryManagerReceiptRecordByID(entity.getReceiptRecordsId());
                managerReceiptMapper.backUpManagerReceiptRecord(managerReceiptRecord.getReceiptRecordsId(), AuthUtils.getUserId());
                managerReceiptMapper.updateManagerReceiptRecordById(entity);
            }
        }else{

            List<ManagerReceiptTable> list =  new ArrayList<>() ;
            List<ManagerPayPlan> paymentPlans =  new ArrayList<>() ;
            //根据采购单id判断是否存在中间表
            if(entity.getPurchaseOrderId() != null){
                ManagerPurchaseOrderVO purchaseOrderVO =  managerPurchaseOrderService.getPurchaseOrdeInfoById(entity.getPurchaseOrderId());
                entity.setPurchaseTopic(purchaseOrderVO.getPurchaseTopic());
                managerReceiptMapper.saveManagerReceiptRecord(entity);
                //查询采购单信息，将收票所需要的信息放入收票记录中并将审批id放入收票记录中
                for (ManagerReceiptTable receiptTable:entity.getReceiptTables()) {
                    receiptTable.setReceiptRecordsId(entity.getReceiptRecordsId());
                    receiptTable.setPurchaseOrderId(entity.getPurchaseOrderId());
                    receiptTable.setApprovalId(approval.getApprovalId());
                    ManagerPayPlan paymentPlan = new ManagerPayPlan();
                    paymentPlan.setPurchaseOrderId(entity.getPurchaseOrderId());
                    paymentPlan.setPlanPeriod(receiptTable.getPlanPeriod());
                    receiptTable.setPayPlanId(managerPaymentPlanService.queryPaymentPlanByPurchaseOrderID(paymentPlan).getPayPlanId());
                    List<ManagerReceiptTable> receiptTableList =queryReceiptTablesByIdAndPlanPeriod(receiptTable);
                    BigDecimal num = new BigDecimal("0");
                    if(receiptTableList.size()>0){
                        for (ManagerReceiptTable rt:receiptTableList) {
                            num= num.add(new BigDecimal(rt.getReceiptMoney())) ;
                        }
                    }else {
                        num= num.add(new BigDecimal(receiptTable.getReceiptMoney()));
                    }
//                    num = num.add(new BigDecimal(receiptTable.getReceiptMoney()));
                    if(num.compareTo(new BigDecimal(receiptTable.getPlanMoney())) == 1){
                        paymentPlan.setReceiveInvoice(0);
                    } else if(num.compareTo(new BigDecimal(receiptTable.getPlanMoney())) == 0) {
                        paymentPlan.setReceiveInvoice(0);
                    } else{
                        paymentPlan.setReceiveInvoice(2);
                    }
//                }
                    paymentPlans.add(paymentPlan);
                    list.add(receiptTable);
                }
                managerPaymentPlanService.updatePayPlansByIdAndPlanPeriod(paymentPlans);
                managerReceiptMapper.updateReceiptTableDataById(list,entity.getReceiptRecordsId());

            }else {
                managerReceiptMapper.saveManagerReceiptRecord(entity);
            }

            //直接保存收票记录数据
        }
        //修改转发人
        if(!CollectionUtils.isEmpty(entity.getTranspondUsers())) {
            transpondEmailService.insertTranspondEmailInfoByUser(entity.getApprovalId(),entity.getTranspondUsers());
        }
        //数据保存完，发送审批邮件给审批人
        //调用通知接口生成待办通知
        if(AuthUtils.getUserAccount().equals(user.getAccount())){
            //跳过第一步审批
            this.approvedManagerReceiptRecord(entity,token,true);
        }else {

            //调用通知接口生成待办通知
            Integer userId = AuthUtils.getUserId();
            CompletableFuture.runAsync(() -> this.pushNotic(approval.getApprovalId(), new Timestamp(System.currentTimeMillis()),
                    userId, 0, 42, user.getUserId(), token));
        }

        return entity;
    }

    @Override
    public PageUtil<ManagerReceiptRecord> queryManagerReceiptRecordsListInfo(IPage<ManagerReceiptRecord> page, ManagerReceiptRecord managerReceiptRecord, List<SysUserEntity> userList, String token) {
        if (managerReceiptRecord.getOrderByProp() != null) {
            managerReceiptRecord.setOrderByProp(StringUtils.camelToUnderline(managerReceiptRecord.getOrderByProp()));
        }
        IPage<ManagerReceiptRecord> iPage = managerReceiptMapper.queryManagerReceiptRecordsListInfo(page, managerReceiptRecord, userList);
        List<ManagerReceiptRecord> list = iPage.getRecords();

        if (!list.isEmpty()) {
            BigDecimal tickerMoneyPage = new BigDecimal(0);
            for (ManagerReceiptRecord rrvo : list) {
                //rrvo.setReceiptTables(this.getReceiptTableDataByReceiptId(rrvo.getReceiptRecordsId()));
                if (StringUtils.isNotEmpty(rrvo.getTickerMoney())) {
                    tickerMoneyPage = tickerMoneyPage.add(new BigDecimal(rrvo.getTickerMoney()));
                }

            }
            list.get(0).setTickerMoneyPage(String.valueOf(tickerMoneyPage));
            iPage.setRecords(list);
        }
        return new PageUtil<>(iPage);
    }

    @Override
    public List<ManagerReceiptRecord> queryManagerReceiptRecord(ManagerReceiptRecord managerReceiptRecord) {
        List<ManagerReceiptRecord> receiptRecordsList =  managerReceiptMapper.queryManagerReceiptRecord(managerReceiptRecord);
        if(receiptRecordsList.size()>0&&receiptRecordsList.get(0).getPurchaseOrderId() != null){
            if(receiptRecordsList.get(0).getReceiptTables().size() == 0) {
                receiptRecordsList =   managerReceiptMapper.queryManagerReceiptRecordedMoneyHistory(managerReceiptRecord);
            }
        }
        if(receiptRecordsList.size()>0){
            receiptRecordsList.get(0).setTranspondUsers(transpondEmailService.queryTranspondByApprovalId(managerReceiptRecord.getApprovalId()));
        }
        return receiptRecordsList;
    }

    @Override
    public Boolean approvedManagerReceiptRecord(ManagerReceiptRecord entity, String token, boolean auto) {
        ApprovalVO approval = approvalService.queryApprovalByAppID(entity.getApprovalId());
        ActivitiVO activitiVO = new ActivitiVO();//最终审批人
        activitiVO.setBusinessId(approval.getBusinessId());
        activitiVO.setAuthorization(AuthUtils.getUserAccount());
        ResponseAPI<ActivitiVO> processNodeNameAndCode = workFlowFeginService.getProcessNodeNameAndCode(activitiVO);

        SysUserEntity user= null ;
        Integer workState;
        String titel;
        String msg;
        Integer todoUser ;
        String ccUser = null;
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        SysUserEntity askUser = feginService.searchUserInfoById(approval.getCreator(),token).getResult();
        if(auto){
            approvalService.insertApprovalLog(approval.getApprovalId(),"通过",
                    "系统判定跳过",entity.getAppReason());
        }else {
            //记录日志
            approvalService.insertApprovalLog(approval.getApprovalId(),"通过",
                    "",entity.getAppReason());
        }
        if( "出纳".equals(processNodeNameAndCode.getResult().getName()) ){
            user=askUser;
            workState = 1;
            todoUser = 0;
            workFlowFeginService.approvalProcessByBusinessId(activitiVO);

            titel = "【系统通知】综管收票记录 - 流程单审批通过通知";
            ccUser = queryReceiptRecordCC();
            if(entity.getPurchaseOrderId()!= null){
                String planPeriod = NumberToCnUtil.strToChineseLower(entity.getPlanPeriod());
                msg="<div><p >" + "尊敬的" + user.getLoginName() + "：</p></div>" +
                        "<div><p style='text-indent: 2em'>您好，您收票记录审批已通过：</p></div>"+
                        "<div><p style='text-indent: 2em'>事项编号："+approval.getApprovalCode()+"</p></div>"+
                        "<div><p style='text-indent: 2em'>采购名称："+entity.getPurchaseTopic()+"</p></div>"+
                        "<div><p style='text-indent: 2em'>采购单编号："+entity.getPurchaseNo()+"</p></div>"+
                        "<div><p style='text-indent: 2em'>收票金额："+entity.getTickerMoney()+"元</p></div>"+
                        "<div><p style='text-indent: 2em'>收票期次：第"+ planPeriod+"期</p></div>"+
                        "<div><p style='text-indent: 2em'>系统查看路径：客户关系管理系统 - 待办事项 - 待办审批 " +
                        "<a href='"+webSitUrl+"/?m=crm&p=crmtodoItems&me=todoApprovalPath'>进入</a></p></div>"+
                        "<div><p style='text-indent: 2em'>谢谢！</p></div>"+
                        "<div><p style='text-indent: 2em'>说明：该邮件为系统自动发送，请勿回复。</p></div>";
            }else{
                msg="<div><p >" + "尊敬的" + user.getLoginName() + "：</p></div>" +
                        "<div><p style='text-indent: 2em'>您好，您收票记录审批已通过：</p></div>"+
                        "<div><p style='text-indent: 2em'>事项编号："+approval.getApprovalCode()+"</p></div>"+
                        "<div><p style='text-indent: 2em'>收票名称："+entity.getPurchaseTopic()+"</p></div>"+
                        "<div><p style='text-indent: 2em'>收票金额："+entity.getTickerMoney()+"元</p></div>"+
                        "<div><p style='text-indent: 2em'>系统查看路径：客户关系管理系统 - 待办事项 - 待办审批 " +
                        "<a href='"+webSitUrl+"/?m=crm&p=crmtodoItems&me=todoApprovalPath'>进入</a></p></div>"+
                        "<div><p style='text-indent: 2em'>谢谢！</p></div>"+
                        "<div><p style='text-indent: 2em'>说明：该邮件为系统自动发送，请勿回复。</p></div>";
            }

            approvalService.approved(null,entity.getApprovalId());
            //记录日志
            String finalCcUser = ccUser;
            SysUserEntity finalUser = user;
            String bccEmail = transpondEmailService.selectTranspondEmailStr(entity.getApprovalId());
            CompletableFuture.runAsync(() -> EmailUtils.sentMailByAddressee(finalUser.getEmail(),finalCcUser+","+bccEmail,titel,msg,token));
            CompletableFuture.runAsync(() -> NoticUtils.pushNotic(entity.getApprovalId(), new Timestamp(System.currentTimeMillis()),
                    approval.getCreator(),workState,42,todoUser,token));
        } else {

            if("行政专员审批".equals(processNodeNameAndCode.getResult().getName())){
                user = dictionaryService.queryMenuUserIdsByCode("personnelManager").get(0);
                activitiVO.getCustomParams().put("personnelManager",user.getAccount());
            }else if("人事经理审批".equals(processNodeNameAndCode.getResult().getName())){
                user = dictionaryService.queryMenuUserIdsByCode("finance").get(0);
                activitiVO.getCustomParams().put("finance",user.getAccount());
            }else if("财务审批".equals(processNodeNameAndCode.getResult().getName())){
                user = dictionaryService.queryMenuUserIdsByCode("cashier").get(0);
                activitiVO.getCustomParams().put("cashier",user.getAccount());
            }

            workFlowFeginService.approvalProcessCustomUserByBusinessId(activitiVO);
            ResponseAPI<ActivitiVO> nextProcessNodeNameAndCode = workFlowFeginService.getProcessNodeNameAndCode(activitiVO);
            if(nextProcessNodeNameAndCode.getResult().getAssignee().equals(processNodeNameAndCode.getResult().getAssignee())){
                this.approvedManagerReceiptRecord(entity,token,true);
            }else{
                workState = 0;
                todoUser = user.getUserId();
                //交由下一审批人处理

                approvalService.updateNextApproverByApprovalId(user.getUserId(),entity.getApprovalId());
                CompletableFuture.runAsync(() -> NoticUtils.pushNotic(entity.getApprovalId(), new Timestamp(System.currentTimeMillis()),
                        approval.getCreator(),workState,42,todoUser,token));
            }

        }
        return true;
    }

    /**
     * 审批驳回
     * @param entity
     * @param token
     * @return
     */
    @Override
    public Boolean rejectionManagerReceiptRecord(ManagerReceiptRecord entity, String token) {
        ApprovalVO approval = approvalService.queryApprovalByAppID(entity.getApprovalId());
        ActivitiVO activitiVO = new ActivitiVO();
        activitiVO.setBusinessId(approval.getBusinessId());
        activitiVO.setAuthorization(AuthUtils.getUserAccount());
        workFlowFeginService.deleteInstance(activitiVO);
        //驳回
        SysUserEntity user = null;
        Integer workState;
        String titel;
        String msg;
        Integer todoUser;
        SysUserEntity askUser = feginService.searchUserInfoById(approval.getCreator(), token).getResult();
        user = askUser;
        workFlowFeginService.deleteInstance(activitiVO);
        if(entity.getPurchaseOrderId() != null){
            this.updateReceiptTableData(approval.getApprovalId());
        }
        //驳回至起点
        workState = 1;
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        titel= "【系统通知】综管收票记录 - 流程单审批驳回通知";
        if(entity.getPurchaseOrderId() != null) {
            String planPeriod = NumberToCnUtil.strToChineseLower(entity.getPlanPeriod());
            msg = "<div><p >" + "尊敬的" + user.getLoginName() + "：</p></div>" +
                    "<div><p style='text-indent: 2em'>您好，您有一张新的收票记录审批已被驳回：</p></div>"+
                    "<div><p style='text-indent: 2em'>事项编号："+approval.getApprovalCode()+"</p></div>"+
                    "<div><p style='text-indent: 2em'>审批人："+ AuthUtils.getUserName()+"</p></div>"+
                    "<div><p style='text-indent: 2em'>审批意见："+ (StringUtils.isEmpty(entity.getAppReason()) ? "" : entity.getAppReason())+"</p></div>"+
                    "<div><p style='text-indent: 2em'>审批时间："+simpleDateFormat.format(new Date())+"</p></div>"+
                    "<div><p style='text-indent: 2em'>采购名称："+entity.getPurchaseTopic()+"</p></div>"+
                    "<div><p style='text-indent: 2em'>采购单编号："+entity.getPurchaseNo()+"</p></div>"+
                    "<div><p style='text-indent: 2em'>收票金额："+entity.getTickerMoney()+"元</p></div>"+
                    "<div><p style='text-indent: 2em'>收票期次：第"+ planPeriod+"期</p></div>"+
                    "<div><p style='text-indent: 2em'>系统查看路径：客户关系管理系统 - 待办事项 - 待办审批 " +
                    "<a href='"+webSitUrl+"/?m=crm&p=crmtodoItems&me=todoApprovalPath'>进入</a></p></div>"+
                    "<div><p style='text-indent: 2em'>谢谢！</p></div>"+
                    "<div><p style='text-indent: 2em'>说明：该邮件为系统自动发送，请勿回复。</p></div>";
        }else{
            msg = "<div><p >" + "尊敬的" + user.getLoginName() + "：</p></div>" +
                    "<div><p style='text-indent: 2em'>您好，您有一张新的收票记录审批已被驳回：</p></div>"+
                    "<div><p style='text-indent: 2em'>事项编号："+approval.getApprovalCode()+"</p></div>"+
                    "<div><p style='text-indent: 2em'>审批人："+ AuthUtils.getUserName()+"</p></div>"+
                    "<div><p style='text-indent: 2em'>审批意见："+ (StringUtils.isEmpty(entity.getAppReason()) ? "" : entity.getAppReason())+"</p></div>"+
                    "<div><p style='text-indent: 2em'>审批时间："+simpleDateFormat.format(new Date())+"</p></div>"+
                    "<div><p style='text-indent: 2em'>收票名称："+entity.getReceiptName()+"</p></div>"+
                    "<div><p style='text-indent: 2em'>收票金额："+entity.getTickerMoney()+"元</p></div>"+
                    "<div><p style='text-indent: 2em'>系统查看路径：客户关系管理系统 - 待办事项 - 待办审批 " +
                    "<a href='"+webSitUrl+"/?m=crm&p=crmtodoItems&me=todoApprovalPath'>进入</a></p></div>"+
                    "<div><p style='text-indent: 2em'>谢谢！</p></div>"+
                    "<div><p style='text-indent: 2em'>说明：该邮件为系统自动发送，请勿回复。</p></div>";
        }

        approvalService.approvalRejection(null,entity.getApprovalId());
        todoUser = 0;
        //记录日志
        approvalService.insertApprovalLog(approval.getApprovalId(),"驳回",
                "",entity.getAppReason());
        SysUserEntity finalUser = user;
        CompletableFuture.runAsync(() -> EmailUtils.sentMailByAddressee(finalUser.getEmail(),null,titel,msg,token));
        Integer userId = AuthUtils.getUserId();
        CompletableFuture.runAsync(() -> NoticUtils.pushNotic(entity.getApprovalId(),  approval.getCreateDataTime(),
                userId,workState,42,todoUser,token));
        return true;
    }

    @Override
    public ManagerReceiptRecord queryManagerReceiptRecordHistory(Integer approvalId) {
        ManagerReceiptRecord managerReceiptRecord = managerReceiptMapper.queryManagerReceiptRecordHistory(approvalId);
        if(managerReceiptRecord == null){
            ManagerReceiptRecord receiptR = new ManagerReceiptRecord();
            receiptR.setApprovalId(approvalId);
            managerReceiptRecord =  this.queryManagerReceiptRecord(receiptR).get(0);
        }
        managerReceiptRecord.setTranspondUsers(transpondEmailService.queryTranspondByApprovalId(approvalId));
        return managerReceiptRecord;
    }

    @Override
    public List<ManagerReceiptTable> queryReceiptTablesByIdAndPlanPeriod(ManagerReceiptTable entity) {
        return managerReceiptMapper.queryReceiptTablesByIdAndPlanPeriod(entity);
    }

    @Override
    public void updateReceiptTableData(Integer approvalId) {
        List<ManagerReceiptTable> receiptTables = managerReceiptMapper.queryReceiptTablesByApprovalId(approvalId);
        List<ManagerPayPlan> paymentPlans = new ArrayList<>();
        List<ManagerReceiptTable> list = new ArrayList<>();
        for (ManagerReceiptTable receiptTable: receiptTables) {
            List<ManagerReceiptTable> receiptTableList =queryReceiptTablesByIdAndPlanPeriod(receiptTable);
            BigDecimal num = new BigDecimal("0");
            ManagerPayPlan paymentPlan = new ManagerPayPlan();
            if(receiptTableList.size()>0){
                for (ManagerReceiptTable rt:receiptTableList) {
                    num= num.add(new BigDecimal(rt.getReceiptMoney())) ;
                }
            }else {
                num= num.add(new BigDecimal(receiptTable.getReceiptMoney()));
            }
            num = num.subtract(new BigDecimal(receiptTable.getReceiptMoney()));
            if(num.compareTo(new BigDecimal("0.00")) !=0){
                if(num.compareTo(new BigDecimal(receiptTable.getPlanMoney())) == 0){
                    paymentPlan.setReceiveInvoice(0);
                } else if(num.compareTo(new BigDecimal(receiptTable.getPlanMoney())) == -1) {
                    paymentPlan.setReceiveInvoice(2);
                } else if(num.compareTo(new BigDecimal(receiptTable.getPlanMoney())) == 1) {
                    paymentPlan.setReceiveInvoice(0);
                }

            }else{
                paymentPlan.setReceiveInvoice(1);
            }
            paymentPlan.setPlanPeriod(receiptTable.getPlanPeriod());
            paymentPlan.setPurchaseId(receiptTable.getPurchaseOrderId());
            paymentPlans.add(paymentPlan);
            list.add(receiptTable);
        }
        managerPaymentPlanService.updatePayPlansByIdAndPlanPeriod(paymentPlans);
        if(list.size()>0){
            managerReceiptMapper.updateReceiptTableData(list, approvalId);
        }
    }

    @Override
    public List<ManagerReceiptRecord> queryReceiptRecordsListInfo(ManagerReceiptRecord entity, List<SysUserEntity> userList, String token) {
        if (entity.getOrderByProp() != null) {
            entity.setOrderByProp(StringUtils.camelToUnderline(entity.getOrderByProp()));
        }
        List<ManagerReceiptRecord> list = managerReceiptMapper.queryReceiptRecordsListInfo(entity, userList);
        return list;
    }

    @Override
    public void exportReceiptRecordsInfo(HttpServletResponse response, List<ManagerReceiptRecord> list, String token)  throws Exception{
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
        List<String> statesList = new ArrayList<>();
        statesList.add("payIsNot");
        statesList.add("inputTaxOrNot");
        statesList.add("ticketType");
        statesList.add("approvalStatus");
        JSONObject userObject = feginService.getUserInfo(token);
        JSONObject jsonObject = feginService.queryDictionaryLookupInfo("crm", statesList);
        List<String> classfiedCode = new ArrayList<>();
        classfiedCode.add("payPlanPeriodNum");
        Map<String, List<DictionaryLookupItemVO>> listMap = dictionaryService.queryDictionaryLookupInfo(1, classfiedCode);
        for (int i = 0; i < list.size(); i++) {
            ManagerReceiptRecord rrVO = list.get(i);
            rrVO.setReceiptRecordsId(i+1);
            if(rrVO.getSupplier()!= null){
                rrVO.setSupplierName(selSupplierName(rrVO.getSupplier().getSupplierId()));
            }
            String str = "";
            String [] planPeriods;
            if(rrVO.getPlanPeriod()!= null && rrVO.getPlanPeriod().indexOf(",")>0){
                planPeriods = rrVO.getPlanPeriod().split(",");
                for ( int j =0 ;j<planPeriods.length ;j ++) {
                    if(j==planPeriods.length -1){
                        str += getCRMDictionaryNameByCode("payPlanPeriodNum",listMap).get(planPeriods[j] )+"";
                    }else{
                        str += getCRMDictionaryNameByCode("payPlanPeriodNum",listMap).get(planPeriods[j] )+",";
                    }

                }
                rrVO.setPlanPeriodName(str);
            }else{
                rrVO.setPlanPeriodName((String)getCRMDictionaryNameByCode("payPlanPeriodNum",listMap).get(rrVO.getPlanPeriod() + ""));
            }
            rrVO.setTicketTypeName((String) getDictionaryNameByCode("ticketType", jsonObject).get(rrVO.getTicketType() + ""));
            rrVO.setInputTaxName((String) getDictionaryNameByCode("inputTaxOrNot", jsonObject).get(rrVO.getInputTax() + ""));
            rrVO.setHandlersName((String)getUserNameById(userObject).get(rrVO.getHandlers().getUserId()));
//            rrVO.setPayIsNotName((String) getDictionaryNameByCode("payIsNot", jsonObject).get(rrVO.getPayIsNot() + ""));

            rrVO.setApprovalStatusName((String)getDictionaryNameByCode("approvalStatus",jsonObject).get(rrVO.getApproval().getApprovalStatus() + ""));
            rrVO.setReceiptDateTime(dateFormat.format(rrVO.getReceiptDate()));
        }
        //获取yml模板位置
        YamlPropertiesFactoryBean factoryBean = new YamlPropertiesFactoryBean();
        String path = "application.yml";
        factoryBean.setResources(new ClassPathResource(path));
        Properties properties = factoryBean.getObject();
        String templatePath = String.valueOf(properties.get("report.managerReceiptRecordTemplate"));
        //依据根目录获取模板位置
        TemplateExportParams params = new TemplateExportParams(templatePath);
        Map<String, Object> map = new HashMap<>();
        map.put("receiptRecordsInfo",list);
        ReportUtils.exportExcel(params,map,"综管收票记录信息",response);
    }

    @Override
    public PageUtil<ManagerReceiptRecord> queryReceiptRecordsApprovalListInfo(IPage<ManagerReceiptRecord> page, ManagerReceiptRecord managerReceiptRecord, String token) {
        if (managerReceiptRecord.getOrderByProp() != null) {
            managerReceiptRecord.setOrderByProp(StringUtils.camelToUnderline(managerReceiptRecord.getOrderByProp()));
        }
        ApprovalVO approvalVO = new ApprovalVO();
        approvalVO.setApprovalType(42);
        List<ApprovalVO> appList = new ArrayList<>();
        if ("todo".equals(managerReceiptRecord.getParamType())) {
            appList = approvalService.queryApprovalByPage(approvalVO);
        } else if ("done".equals(managerReceiptRecord.getParamType())) {
            appList = approvalService.queryApprovalDoneRecordByType(approvalVO);
        } else {
            appList = approvalService.queryApprovalRecordByType(approvalVO, token);
        }
        if (appList == null || appList.isEmpty()) {
            return new PageUtil(new PageDTO());
        } else {
            ArrayList<Integer> arrayList = new ArrayList<>();
            for (ApprovalVO item : appList) {
                arrayList.add(item.getApprovalId());
            }
            if (arrayList.size() > 0) {
                managerReceiptRecord.setApprovalIds(arrayList);
            } else {
                arrayList.add(0);
                managerReceiptRecord.setApprovalIds(arrayList);
            }
            IPage<ManagerReceiptRecord> iPage = managerReceiptMapper.queryManagerReceiptRecordsListInfo(page, managerReceiptRecord, null);
            List<ManagerReceiptRecord> list = iPage.getRecords();

            if (!list.isEmpty()) {
                BigDecimal tickerMoneyPage = new BigDecimal(0);
                for (ManagerReceiptRecord rrvo : list) {
                    //rrvo.setReceiptTables(this.getReceiptTableDataByReceiptId(rrvo.getReceiptRecordsId()));
                    if (StringUtils.isNotEmpty(rrvo.getTickerMoney())) {
                        tickerMoneyPage = tickerMoneyPage.add(new BigDecimal(rrvo.getTickerMoney()));
                    }

                }
                list.get(0).setTickerMoneyPage(String.valueOf(tickerMoneyPage));
                iPage.setRecords(list);
            }
            return new PageUtil<>(iPage);
        }
    }

    @Override
    public Boolean deleteReceiptRecordById(Integer receiptRecordsId) {
        return managerReceiptMapper.deleteReceiptRecordById(receiptRecordsId);
    }

    /**
     * 开启审批流程
     * @param
     * @param user
     * @return
     */
    private Integer startManagerReceiptRecordApproval(SysUserEntity user){
        ActivitiVO activitiVO = new ActivitiVO();
        activitiVO.setAuthorization(AuthUtils.getUserAccount());
        activitiVO.setProcessName("综管收票审批");
        activitiVO.setProcessCode("manager_receipt_record_approval");
        activitiVO.setNextNodeParams("administrativeSpecialist");
        //行政专员
        SysUserEntity business = dictionaryService.queryMenuUserIdsByCode("administrativeSpecialist").get(0);
        activitiVO.setNextNodeAssignee(business.getAccount());
        ResponseAPI<ActivitiVO> responseAPI = workFlowFeginService.startMaxVersionProcessByDesignCodeCustomParams(activitiVO);
        return responseAPI.getResult().getBusinessId();
    }

    private void pushNotic(Integer workflowId, Timestamp askTime,Integer askUserId,
                           Integer workState,Integer taskType,Integer todoUserId,String token){
        NoticVo vo = new NoticVo();
        vo.setFromSystem("crm");
        vo.setWorkflowId(workflowId);
        vo.setAskUserId(askUserId);
        vo.setAskTime(askTime);
        vo.setWorkState(workState);
        vo.setTaskType(taskType);
        vo.setTodoUserId(todoUserId);
        feginMessageService.pushNoticToDB(token,vo);
    }


    /**
     * 获取综管收票记录抄送人
     * @return
     */
    private String queryReceiptRecordCC(){
        //获取抄送人
        List<SysUserEntity> userIds = dictionaryService.queryCcUserIdsByCode("managerReceiptRecordCC");
        StringBuilder emailList = new StringBuilder();
        for (int i = 0; i < userIds.size(); i++) {
            if (userIds.size()-1 == i){
                emailList.append(userIds.get(i).getEmail());
            }else {
                emailList.append(userIds.get(i).getEmail());
                emailList.append(",");
            }
        }
        return emailList.toString();
    }

    private String selSupplierName(Integer supplierId) {
        List<SupplierVO> list = productInfoMapper.querySuppliers();
        if (!CollectionUtils.isEmpty(list)) {
            for (SupplierVO item : list) {
                if (item.getSupplierId().equals(supplierId)) {
                    return item.getSupplierName();
                }
            }
            return null;
        }
        return null;
    }

    private Map getCRMDictionaryNameByCode(String itemCode, Map listMap) {
//        LinkedHashMap linkedHashMap = (LinkedHashMap) listMap.get("result");
        List<DictionaryLookupItemVO> dataDictionaryArray = (List) listMap.get(itemCode);
        Map<String, String> map = new HashMap<>();
        if (!CollectionUtils.isEmpty(dataDictionaryArray)) {
            for (DictionaryLookupItemVO item : dataDictionaryArray) {
                map.put(item.getItemCode(), item.getItemName());
            }
            return map;
        }
        return null;
    }

    private Map getDictionaryNameByCode(String itemCode, JSONObject jsonObject) {
        LinkedHashMap linkedHashMap = (LinkedHashMap) jsonObject.get("result");
        List<Map> dataDictionaryArray = (List) linkedHashMap.get(itemCode);
        Map<String, String> map = new HashMap<>();
        if (!CollectionUtils.isEmpty(dataDictionaryArray)) {
            for (Map item : dataDictionaryArray) {
                map.put(item.get("itemCode").toString(), item.get("itemName").toString());
            }
            return map;
        }
        return null;
    }

    private Map getUserNameById(JSONObject jsonObject) {
        List<Map> dataDictionaryArray = (List) jsonObject.get("result");
        Map<Integer, String> map = new HashMap<>();
        if (!CollectionUtils.isEmpty(dataDictionaryArray)) {
            for (Map item : dataDictionaryArray) {
                map.put((Integer) item.get("userId"), (String) item.get("loginName"));
            }
            return map;
        }
        return null;
    }
}
